// src/main/auth.ts
import Store from 'electron-store'

const store = new Store()

const TOKEN_KEY = 'app_cahce$_userToken'
const LOGIN_TIME_KEY = 'app_cahce$_lastVisitedDate'

export function getToken(): string | null {
  const token = store.get(TOKEN_KEY)
  return typeof token === 'string' ? token : null
}

export function setToken(token: string): void {
  store.set(TOKEN_KEY, token)
  store.set(LOGIN_TIME_KEY, Date.now())
}

export function clearToken(): void {
  store.delete(TOKEN_KEY)
  store.delete(LOGIN_TIME_KEY)
}

export function isTokenExpired(): boolean {
  const time = store.get(LOGIN_TIME_KEY)
  if (typeof time !== 'number') return true
  return Date.now() - time > 24 * 60 * 60 * 1000
}

export function isLoggedIn(): boolean {
  const token = getToken()
  return !!token && !isTokenExpired()
}
